package com.yenroc.ho.interceptor;

import com.yenroc.ho.consts.CommonConsts;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class IHandlerInterceptor  implements HandlerInterceptor {
    private org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(IHandlerInterceptor.class);

    public IHandlerInterceptor() {
    }

    /**
     * 重写线程名称, 依据 线程名称 进行接口的传递,作为一整条 接口的调用链
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (StringUtils.isEmpty(request.getHeader(CommonConsts.THREAD_ID))) {
            String logId = System.currentTimeMillis() + UUID.randomUUID().toString().toUpperCase().substring(0, 5);
            Thread.currentThread().setName(logId);
        } else {
            Thread.currentThread().setName(request.getHeader(CommonConsts.THREAD_ID));
        }
        log.info("request请求地址path=[{}],uri=[{}]", request.getServletPath(), request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
